﻿using System;
using System.Linq;
using System.Web.Mvc;
using Icms.Core.Model;
using Icms.Core.Repository;

namespace Icms.WebUI.Controllers
{
    public class SyncController : BaseController
    {
        private readonly IRepo<Message> messageRepo;

        public SyncController(IRepo<Message> messageRepo)
        {
            this.messageRepo = messageRepo;
        }

        [Authorize]
        public ActionResult GetNewMessages()
        {
            var userId = Globals.User().Id;
            var c = messageRepo.Where(o => o.RecipientId == userId && o.IsRead == false).Count();
            var olist = messageRepo
                .Where(o => o.RecipientId == userId && o.IsRead == false && o.IsRecipientNotified == false);

            var list = olist.Select(o => new { o.Subject }).ToList();

            foreach (var message in olist)
            {
                message.IsRecipientNotified = true;
            }
            messageRepo.Save();

            return Json(new { Count = c, List = list });
        }

        public ActionResult Am()
        {
            messageRepo.Insert(new Message { DateSent = DateTime.Now, Subject = "asdfa", Text = "ada", RecipientId = Globals.User().Id });
            messageRepo.Save();
            return new EmptyResult();
        }
    }
}